﻿using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace com.uplus.rabbitmqhelper
{
    public class RabbitMQConsumer: RabbitMQProductor
    {
        #region 绑定消费者（需要先创建队列，或者保证队列已存在，否则会报错）
        /// <summary>
        /// 绑定消费者（需要先创建队列，或者保证队列已存在，否则会报错）
        /// </summary>
        /// <param name="queueName">队列名称</param>
        /// <returns>返回创建后的消费者，</returns>
        /// Creator:LM  Time:2018年3月21日16:48:06
        public EventingBasicConsumer BindConsumer(string queueName)
        {
            try
            {
                if (channel != null)
                {
                    channel.BasicQos(0, 1, false);
                    var consumer = new EventingBasicConsumer(channel);
                    channel.BasicConsume(queueName, false, consumer);
                    return consumer;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 绑定链接消费者（需要先创建队列，或者保证队列已存在，否则会报错）
        /// <summary>
        /// 绑定消费者（需要先创建队列，或者保证队列已存在，否则会报错）
        /// </summary>
        /// <param name="queueName">队列名称</param>
        /// <returns>返回创建后的消费者，</returns>
        /// Creator:LM  Time:2018年3月21日16:48:06
        public BasicGetResult BindBasicConsumer(string queueName)
        {
            try
            {
                if (channel != null)
                {
                    channel.BasicQos(0, 1, false);
                    var consumer = channel.BasicGet(queueName, true);
                    return consumer;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 消息确认
        /// <summary>
        /// 消息确认
        /// </summary>
        /// <param name="e"></param>
        public void AffirmMsg(BasicDeliverEventArgs e)
        {
            try
            {
                channel.BasicAck(e.DeliveryTag, false);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 消息拒收
        /// <summary>
        /// 消息拒收
        /// </summary>
        /// <param name="e"></param>
        /// <param name="back">是否重新插入队列</param>
        public void RejectMsg(BasicDeliverEventArgs e, bool back)
        {
            try
            {
                channel.BasicReject(e.DeliveryTag, back);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
    }
}
